from dao.address import address_dao
from schemas import Response


class AddressService:

    @classmethod
    async def add_address(cls, user_input):
        if user := await address_dao.get(pk=user_input.user_id):
            if await address_dao.get_user_address(user.id) >= 20:
                return Response(code=400, errmsg='收获地址数量(个)已满20')
            return await address_dao.create_address(user_input)
        return Response(code=400, errmsg='用户不存在')

    @classmethod
    async def del_address(cls, pk):
        try:
            await address_dao.del_address(pk)
            return Response()
        except Exception:
            return Response(code=400, errmsg='地址不存在')

    @classmethod
    async def address_arr(cls, user_id):
        data = await address_dao.arr_address(user_id)
        return Response(data=data)

    @classmethod
    async def put_address(cls, pk, user_input):
        try:
            await address_dao.update_address(pk, user_input)
            return Response()
        except Exception:
            return Response(code=400, errmsg='地址不存在')

    @classmethod
    async def default_set(cls, pk, user_id):
        try:
            await address_dao.set_default(pk, user_id)
            return Response()
        except Exception as e:
            print(e)
            return Response(code=400, errmsg='用户不存在')